package org.advanced.lock;

import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;

import java.util.concurrent.TimeUnit;

/**
 * @author John.zhang
 * @version Id: RedissonLock, v 1.0 2020/12/21 14:55 ZhiYong Exp $
 * redis分布式锁
 */
public class RedissonLock {
    private static RedissonClient redissonClient;

    static {
        Config config = new Config();
        config.useSingleServer().setAddress("redis://127.0.0.1:6379");
        redissonClient = Redisson.create(config);
    }

    public static void main(String[] args) throws InterruptedException {
        RLock rLock = redissonClient.getLock("updateAccount");
        int wait = 100;
        int max = 10;
        // 最多等待100秒、上锁10s以后自动解锁
        if (rLock.tryLock(wait, max, TimeUnit.SECONDS)) {
            System.out.println("获取锁成功");
        }
        Thread.sleep(20000);
        rLock.unlock();

        redissonClient.shutdown();
    }
}
